﻿using System;
using System.Collections.Generic;
using System.Linq;
using System.Web;
using System.Web.Security;
using WebMobie.Modules.Query;

namespace WebMobie.Modules.Role
{
	public class RoleManager
	{
		private readonly UserInfo userinfo = new UserInfo();
		/// <summary>
		///     Add all underlying roles
		/// </summary>
		/// <param name="log"></param>
		/// <param name="role"></param>
		public void AddRole(string log, string role)
		{
			if (String.IsNullOrWhiteSpace(log) || String.IsNullOrWhiteSpace(role))
			{
				return;
			}
			if (userinfo.IsUserExist(log))
			{
				if (!Roles.IsUserInRole(log, role))
				{
					Roles.AddUserToRole(log, role);
				}
			}
			else
			{
				throw new Exception("User doesn't exist.");
			}
		}
		/// <summary>
		///     Fastest way to verify and add or remove role.
		///     Add also all underlying roles.
		/// </summary>
		/// <param name="log"></param>
		/// <param name="role"></param>
		/// <param name="status"></param>
		public void VerifyAddRemoveRole(string log, string role, bool previousStatus, bool currentStatus)
		{
			if (String.IsNullOrWhiteSpace(log) || String.IsNullOrWhiteSpace(role))
			{
				return;
			}
			if (!Roles.RoleExists(role))
			{
				Roles.CreateRole(role);
			}
			bool add = !previousStatus && currentStatus;

			if (currentStatus == true)
			{
				if (!Roles.IsUserInRole(log, role))
					Roles.AddUserToRole(log, role);
			}
			else
			{
				if (Roles.IsUserInRole(log, role))
				{
					Roles.RemoveUserFromRole(log, role);
				}
			}
		}
	}
}